import 'package:catsao/mock/video.dart';
import 'package:catsao/pages/searchPage.dart';
import 'package:catsao/pages/userPage.dart';
import 'package:catsao/util/event_bus.dart';
import 'package:catsao/views/tikTokCommentBottomSheet.dart';
import 'package:catsao/views/tikTokHeader.dart';
import 'package:catsao/views/tikTokScaffold.dart';
import 'package:catsao/views/tikTokVideo.dart';
import 'package:catsao/views/tikTokVideoButtonColumn.dart';
import 'package:catsao/views/tikTokVideoPlayer.dart';
import 'package:catsao/views/tiktokTabBar.dart';
import 'package:fijkplayer/fijkplayer.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:safemap/safemap.dart';
import 'package:catsao/style/theme.dart';

/// 单独修改了bottomSheet组件的高度
import 'package:catsao/other/bottomSheet.dart' as CustomBottomSheet;

class TictokHomePage extends StatefulWidget {
  const TictokHomePage({
    Key key,
    this.showheader:true,
    this.currentvideoid,
  }) : super(key: key);
  final int currentvideoid;
  final bool showheader;

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<TictokHomePage> with WidgetsBindingObserver {
  TikTokPageTag tabBarType = TikTokPageTag.video;

  TikTokScaffoldController tkController = TikTokScaffoldController();

  PageController _pageController;

  ScrollController scrollController;
  VideoListController _videoListController = VideoListController();

  /// 记录点赞
  Map<int, bool> favoriteMap = {};

  List<UserVideo> videoDataList = [];

  int currentIndex = 0;

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) async {
    if (state != AppLifecycleState.resumed) {
      _videoListController.currentPlayer.pause();
    }
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    _videoListController.currentPlayer.pause();
    if (widget.currentvideoid == null) {
      eventBus.destroy();
    }
    super.dispose();
  }

  @override
  void initState() {
    videoDataList = UserVideo.fetchVideo();
    _pageController = PageController(
        initialPage: widget.currentvideoid == null ? 0 : widget.currentvideoid);
    WidgetsBinding.instance.addObserver(this);
    _videoListController.init(
      _pageController,
      videoDataList,
      widget.showheader
    );

    eventBusVideocontroll();

    super.initState();
  }

  void eventBusVideocontroll() {
    //监听tabbar播放
    eventBus.on<EventBusVideoPlay>().listen((event) {
      if (event.videocontroll == "play") {
        _videoListController.currentPlayer.start();
      }
      if (event.videocontroll == "pause") {
        _videoListController.currentPlayer.pause();
      }
    });
    //监听视频列表跳转(待优化)
    eventBus.on<EventBusVideoId>().listen((event) {
      setState(() {
        currentIndex = int.parse(event.videoid);
      });

      // _pageController.animateToPage(currentIndex,
      //     duration: Duration(milliseconds: 200), curve: Curves.easeIn);
      _pageController.jumpToPage(currentIndex);
    });
  }

  @override
  Widget build(BuildContext context) {
    Widget currentPage;

    double a = MediaQuery.of(context).size.aspectRatio;
    bool hasBottomPadding = a < 0.55;

    bool hasBackground = hasBottomPadding;
    hasBackground = tabBarType != TikTokPageTag.home;
    if (hasBottomPadding) {
      hasBackground = true;
    }

    var userPage = UserPage(
      isSelfPage: false,
      canPop: true,
      onPop: () {
        tkController.animateToMiddle();
      },
    );
    var searchPage = SearchPage(
      onPop: tkController.animateToMiddle,
    );
    var header = tabBarType == TikTokPageTag.video
        ? TikTokHeader(
            onSearch: () {
              tkController.animateToLeft();
            },
          )
        : Container();

    // 组合
    return Theme(
        data: ThemeColor.themecolor,
        child: TikTokScaffold(
          controller: tkController,
          hasBottomPadding: hasBackground,
          header: widget.showheader?header:Text(""),
          leftPage: searchPage,
          rightPage: userPage,
          enableGesture: tabBarType == TikTokPageTag.home,
          currentIndex: currentIndex,
          // onPullDownRefresh: _fetchData,
          page: Stack(
            // index: currentPage == null ? 0 : 1,
            children: <Widget>[
              PageView.builder(
                key: Key('home'),
                controller: _pageController,
                pageSnapping: true,
                physics: ClampingScrollPhysics(),
                scrollDirection: Axis.vertical,
                itemCount: _videoListController.videoCount,
                itemBuilder: (context, i) {
                  // 拼一个视频组件出来
                  var data = videoDataList[i];
                  bool isF = SafeMap(favoriteMap)[i].boolean ?? false;
                  var player = _videoListController.playerOfIndex(i);
                  // 右侧按钮列
                  Widget buttons = TikTokButtonColumn(
                    isFavorite: isF,
                    onAvatar: () {
                      widget.showheader?tkController.animateToPage(TikTokPagePositon.right): Navigator.of(context).pop();
                    },
                    onFavorite: () {
                      setState(() {
                        favoriteMap[i] = !isF;
                      });
                      // showAboutDialog(context: context);
                    },
                    onComment: () {
                      CustomBottomSheet.showModalBottomSheet(
                        backgroundColor: Colors.white.withOpacity(0),
                        context: context,
                        builder: (BuildContext context) =>
                            TikTokCommentBottomSheet(),
                      );
                    },
                    onShare: () {},
                  );
                  // video
                  Widget currentVideo = Center(
                    child: FijkView(
                      player: player,
                      color: Colors.black,
                      panelBuilder: (_, __, ___, ____, _____) => Container(),
                    ),
                  );

                  currentVideo = TikTokVideoPage(
                    hidePauseIcon: player.state != FijkState.paused,
                    aspectRatio: 9 / 16.0,
                    key: Key(data.url + '$i'),
                    tag: data.url,
                    bottomPadding: hasBottomPadding ? 16.0 : 16.0,
                    userInfoWidget: VideoUserInfo(
                      desc: data.desc,
                      bottomPadding: hasBottomPadding ? 16.0 : 50.0,
                      // onGoodGift: () => showDialog(
                      //   context: context,
                      //   builder: (_) => FreeGiftDialog(),
                      // ),
                    ),
                    onSingleTap: () async {
                      if (player.state == FijkState.started) {
                        await player.pause();
                      } else {
                        await player.start();
                      }
                      setState(() {});
                    },
                    onAddFavorite: () {
                      setState(() {
                        favoriteMap[i] = true;
                      });
                    },
                    rightButtonColumn: buttons,
                    video: currentVideo,
                  );
                  return currentVideo;
                },
              ),
              Opacity(
                opacity: 1,
                child: currentPage ?? Container(),
              ),
              // Center(
              //   child: Text(_currentIndex.toString()),
              // )
            ],
          ),
        ));
  }
}
